package com.sharedpreferences;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class UserDAO {
	private static UserDAO instance;
	private static UserDB userDB;
	private final static String[] columns = { "id", "username", "password" };

	private final static int ID = 0;
	private final static int USERNAME = 1;
	private final static int PASSWORD = 2;

	private final static String nombreTabla = "user";

	private UserDAO(Context context) {
		userDB = new UserDB(context, "GamesBD", null, 1);
	}

	public static void init(Context context) {
		instance = new UserDAO(context);
	}

	public static UserDAO getInstance() {
		return instance;
	}

	public boolean changeUser(User user) {
		if (getUser() != null) {
			borrarUser();
		}
		if (insertUser(user) != -1) {
			return true;
		}
		return false;

	}

	public void borrarUser() {
		SQLiteDatabase db = userDB.getWritableDatabase();

		db.execSQL("delete from " + nombreTabla);

		db.close();
	}

	public long insertUser(User user) {
		SQLiteDatabase db = userDB.getWritableDatabase();

		ContentValues registro = transformToRegistro(user);
		long retorno = db.insert(nombreTabla, null, registro);

		db.close();
		return retorno;
	}

	public long updateUser(User user) {
		SQLiteDatabase db = userDB.getWritableDatabase();

		ContentValues registro = transformToRegistro(user);
		long retorno = db.update(nombreTabla, registro, "id=" + user.getId(),
				null);

		db.close();
		return retorno;
	}

	public User getUser() {
		SQLiteDatabase db = userDB.getReadableDatabase();

		User user = transformToUser(db.rawQuery("select * from " + nombreTabla,
				null));
		db.close();
		return user;
	}

	private ContentValues transformToRegistro(User user) {
		ContentValues registro = new ContentValues();
		registro.put(columns[ID], user.getId());
		registro.put(columns[USERNAME], user.getUsername());
		registro.put(columns[PASSWORD], user.getPassword());
		return registro;
	}

	private User transformToUser(Cursor cursor) {
		User user = null;
		if (cursor.moveToFirst()) {
			user = new User();
			user.setId(cursor.getInt(ID));
			user.setUsername(cursor.getString(USERNAME));
			user.setPassword(cursor.getString(PASSWORD));
		}
		return user;
	}

}
